package com.polaris.live.ui.party.utils

import androidx.lifecycle.LifecycleOwner
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.im.manager.ImLiveManager
import com.polaris.live.im.manager.OnLiveObserveListener
import com.polaris.live.im.sfs.COMMAND_LIVE_CLOSE
import com.polaris.live.im.sfs.COMMAND_LIVE_FLOATING
import com.polaris.live.im.sfs.COMMAND_LIVE_NOTICE
import com.polaris.live.im.sfs.bean.live.SendLiveCloseMessage
import com.polaris.live.im.sfs.bean.live.SendLiveFloatingMessage
import com.polaris.live.im.sfs.bean.live.SendLiveNoticeMessage
import com.polaris.live.ui.party.listener.PartyImListener

/**
 *  聊天房IM消息帮助类
 * @author Created by 天晴 on 2024/2/28 14:20
 * @since 1.0.0
 **/
class PartyImProxy(
    var mLiveId: Long,
    var mAnchorId: Long,
    var mPartyImListener: PartyImListener? = null,
) {
    companion object {
        fun create(
            liveId: Long,
            mAnchorId: Long,
            mPartyImListener: PartyImListener?,
            owner: LifecycleOwner
        ): PartyImProxy {
            return PartyImProxy(liveId, mAnchorId, mPartyImListener).apply {
                observe(owner)
            }
        }

    }

    fun observe(owner: LifecycleOwner) {
        /**
         * 主播添加通知消息
         */
        if (mAnchorId == UserManager.getUserId()) {
            //直播间通知消息
            ImLiveManager.observe<SendLiveNoticeMessage>(
                owner,
                COMMAND_LIVE_NOTICE,
                { OnLiveObserveListener.ANY_ID }
            ) {
                mPartyImListener?.noticeMessage(it)
            }
        }

        //直播飘屏
        ImLiveManager.observe<SendLiveFloatingMessage>(
            owner,
            COMMAND_LIVE_FLOATING,
            { OnLiveObserveListener.ANY_ID }) {
            mPartyImListener?.floatingMessage(it)
        }

        //直播关闭消息
        ImLiveManager.observe<SendLiveCloseMessage>(
            owner,
            COMMAND_LIVE_CLOSE,
            { mLiveId }) {
            mPartyImListener?.closeRoomMessage(it)
        }
        //直播用户加入消息
        ImLiveManager.observeEvent(owner) { command, argument ->
            mPartyImListener?.liveEvent(command, argument)
        }
        //直播公屏消息
        ImLiveManager.observePublicMessage(owner, { mLiveId }, { message ->
            mPartyImListener?.publicMessage(message)
        })
        //直播变量变化
        ImLiveManager.observeVariableUpdate(owner, { mAnchorId }, {
            mPartyImListener?.variableUpdate(it)
        })
        //直播人数变化
        ImLiveManager.observeUserCountChange(owner, { mAnchorId }, {
            mPartyImListener?.userCountChange(it)
        })
    }

}